<template>
  <el-card>
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="basic">
        <basic-info-form ref="basicInfo" :info="info" />
      </el-tab-pane>
      <el-tab-pane label="生成信息" name="genInfo">
        <gen-info-form ref="genInfo" :info="info" :tables="tables" :menus="menus"/>
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="columnInfo">
        <el-alert
          title="拖拽序号，可调整字段位置"
          type="success"
          :closable="false">
        </el-alert>
        <div class="columnInfo-box">
          <el-table ref="dragTable"
                    class="column-table" :data="columns" row-key="columnId" :max-height="tableHeight"
                    highlight-current-row
                    @current-change="columnTableCurrentChange"
          >
            <el-table-column label="序号" type="index" min-width="20px" class-name="allowDrag" />
            <el-table-column
              label="英文字段名"
              prop="columnName"
              min-width="50px"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="字段类型" min-width="60px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.columnType"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="中文字段名" min-width="100px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.columnComment"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="描述" min-width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.columnDesc"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div class="column-config">
<!--            <div class="title">属性配置</div>-->
            <el-form class="column-form" size="small" label-width="90px" v-if="nowColumnTableRow!=null"
                     :style="{height:tableHeight}">
              <el-form-item label="组件类型">
                <el-select v-model="nowColumnTableRow.htmlType">
                  <el-option label="文本框" value="input" />
                  <el-option label="搜索文本框" value="searchInput" />
                  <el-option label="文本域" value="textarea" />
                  <el-option label="数字类型" value="number" />
<!--                  <el-option label="小数类型" value="decimals" />-->
<!--                  <el-option label="小数类型（保留2位）" value="decimals2" />-->
                  <el-option label="下拉框" value="select" />
                  <el-option label="多选下拉框" value="multipleSelect" />
                  <el-option label="单选框" value="radio" />
                  <el-option label="复选框" value="checkbox" />
<!--                  <el-option label="日期控件(新)" value="date"/>-->
                  <el-option label="日期时间控件" value="datetime" />
                  <el-option label="富文本控件" value="tinymce" />
                  <el-option label="计数器" value="inputNumber" />
                </el-select>
              </el-form-item>

              <el-form-item label="字典类型" v-if="nowColumnTableRow.htmlType=='select' || nowColumnTableRow.htmlType=='multipleSelect' || nowColumnTableRow.htmlType=='radio'  || nowColumnTableRow.htmlType=='checkbox'">
                <el-select v-model="nowColumnTableRow.dictType" clearable filterable placeholder="请选择">
                  <el-option
                    v-for="dict in dictOptions"
                    :key="dict.dictType"
                    :label="dict.dictName"
                    :value="dict.dictType">
                    <span style="float: left">{{ dict.dictName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                  </el-option>
                </el-select>
              </el-form-item>

              <!-------------------------------查询配置------------------------------- -->
              <el-divider class="config-divider">查询配置</el-divider>
              <el-form-item label="查询">
                <el-checkbox true-label="1" v-model="nowColumnTableRow.isQuery">数据查询区域，是否展示</el-checkbox>
              </el-form-item>
              <el-form-item label="查询方式">
                <el-select v-model="nowColumnTableRow.queryType">
                  <el-option label="等于" value="EQ" />
<!--                  <el-option label="!=" value="NE" />-->
<!--                  <el-option label=">" value="GT" />-->
<!--                  <el-option label=">=" value="GTE" />-->
<!--                  <el-option label="<" value="LT" />-->
<!--                  <el-option label="<=" value="LTE" />-->
                  <el-option label="模糊匹配" value="LIKE" />
<!--                  <el-option label="BETWEEN" value="BETWEEN" />-->
                </el-select>
              </el-form-item>

              <!-------------------------------列表展示------------------------------- -->
              <el-divider class="config-divider">列表展示</el-divider>
              <el-form-item label="列表展示">
                <el-checkbox true-label="1" v-model="nowColumnTableRow.isList">数据列表中是否展示</el-checkbox>
              </el-form-item>
              <el-form-item label="列表宽度">
                <el-input v-model="nowColumnTableRow.columnWidth"></el-input>
              </el-form-item>
              <el-form-item label="对齐方式">
                <el-select v-model="nowColumnTableRow.columnAlign">
                  <el-option label="居左" value="left" />
                  <el-option label="居中" value="center" />
                  <el-option label="居右" value="right" />
                </el-select>
              </el-form-item>

              <template v-if="false">
                <!-------------------------------表单配置------------------------------- -->
                <el-divider class="config-divider">表单配置</el-divider>
                <el-form-item label="录入数据">
                  <el-checkbox true-label="1" v-model="nowColumnTableRow.isInsert">新增数据时，能否录入数据</el-checkbox>
                </el-form-item>
                <el-form-item label="编辑数据">
                  <el-checkbox true-label="1" v-model="nowColumnTableRow.isEdit">是否支持编辑数据</el-checkbox>
                </el-form-item>
                <el-form-item label="是否必填">
                  <el-checkbox true-label="1" v-model="nowColumnTableRow.isRequired">是否必填</el-checkbox>
                </el-form-item>
                <!-------------------------------其他配置------------------------------- -->
                <el-divider class="config-divider">其他配置</el-divider>
                <el-form-item label="默认值">
                  <el-input  placeholder="请输入默认值" v-model="nowColumnTableRow.columnDefault"/>
                </el-form-item>

                <el-form-item label="业务表名" v-if="nowColumnTableRow.htmlType=='searchInput'">
                  <el-select v-model="nowColumnTableRow.searchModel" clearable filterable placeholder="请选择">
                    <el-option
                      v-for="(table, index) in tables"
                      :key="index"
                      :label="table.tableName + '：' + table.tableComment"
                      :value="table.modulePath"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <!-------------------------------实体类型------------------------------- -->
                <el-divider class="config-divider">实体类型</el-divider>
                <el-form-item label="Java类型">
                  <el-input v-model="nowColumnTableRow.javaType" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="Java属性名">
                  <el-input v-model="nowColumnTableRow.javaField" :disabled="true"></el-input>
                </el-form-item>
              </template>

            </el-form>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="表单信息" name="formBuildInfo" v-if="isShowFormBuildInfo">
        <form-build v-if="formBuildKey!=null" ref="formBuildInfo"
                    :formBuildKey="formBuildKey"
                    buildType="TableModel"
                    :tables="tables"
                    :columns="columns"
                    :dictOptions="dictOptions"/>
      </el-tab-pane>
    </el-tabs>
    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getGenTable, updateGenTable } from "@/api/tool/gen";
import { optionselect as getDictOptionselect } from "@/api/system/dict/type";
import { listMenu as getMenuTreeselect } from "@/api/system/menu";
import basicInfoForm from "./basicInfoForm";
import genInfoForm from "./genInfoForm";
import Sortable from 'sortablejs'

export default {
  name: "GenEdit",
  components: {
    basicInfoForm,
    genInfoForm,
    //表单设计器
    FormBuild: () => import('@/views/youshuda/components/FormBuild/index')
  },
  data() {
    return {
      // 选中选项卡的 name
      activeName: "formBuildInfo",
      //是否显示表单配置
      isShowFormBuildInfo: false,
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 290 + "px",
      // 表信息
      tables: [],
      // 表列信息
      columns: [],
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      // 表详细信息
      info: {},
      // 表单设计唯一KEY
      formBuildKey: null,
      // 字段表格当前点击的行信息
      nowColumnTableRow: null
    };
  },
  created() {
    const tableId = this.$route.params && this.$route.params.tableId;
    if (tableId) {
      //打开加载框
      this.openLoading();
      let menuId = '';
      if(this.$route.query.redirect){
        let _redirectPath = this.$route.query.redirect;
        _redirectPath=_redirectPath.substring(_redirectPath.lastIndexOf("/"))
        if(_redirectPath.indexOf("_")){
          menuId = "_"+_redirectPath.split("_")[1];
        }
      }
      // 获取表详细信息
      getGenTable(tableId).then(res => {
        this.columns = res.data.rows;
        this.info = res.data.info;
        // 选中选项卡的 name
        this.activeName = "columnInfo"
        if(this.info['genType'] == '2'){
          this.activeName = "formBuildInfo"
        }
        this.tables = res.data.tables;
        this.formBuildKey=this.info['className']+menuId;
        this.$refs.dragTable.setCurrentRow(this.columns[0]);
      });
      /** 查询字典下拉列表 */
      getDictOptionselect().then(response => {
        this.dictOptions = response.data;
      });
      /** 查询菜单下拉列表 */
      getMenuTreeselect().then(response => {
        this.menus = this.handleTree(response.data, "menuId");
      });
      //关闭加载框
      this.closeLoading();
    }
  },
  methods: {
    /** 提交按钮 */
    submitForm() {
      this.openLoading();

      const basicForm = this.$refs.basicInfo.$refs.basicInfoForm;
      const genForm = this.$refs.genInfo.$refs.genInfoForm;
      //表单设计信息
      let fromBuildConfig = null
      let clientType = ''
      if(this.info['genType'] == '2'){
        fromBuildConfig = this.$refs.formBuildInfo.drawingList;
        clientType = this.$refs.formBuildInfo.clientType;
      }
      Promise.all([basicForm, genForm].map(this.getFormPromise)).then(res => {
        const validateResult = res.every(item => !!item);
        if (validateResult) {
          const genTable = Object.assign({}, basicForm.model, genForm.model);
          genTable.columns = this.columns;
          genTable.params = {
            treeCode: genTable.treeCode,
            treeName: genTable.treeName,
            treeParentCode: genTable.treeParentCode,
            parentMenuId: genTable.parentMenuId
          };
          //组装表单设计配置信息
          genTable.fromBuildConfig = fromBuildConfig;
          genTable.clientType = clientType;
          genTable.formBuildKey = this.formBuildKey;

          updateGenTable(genTable).then(res => {
            this.$modal.msgSuccess(res.msg);
            if (res.code === 200) {
              this.close();
            }
          }).finally(res => {
            //关闭加载框
            this.closeLoading();
          });
        } else {
          this.$modal.msgError("表单校验未通过，请重新检查提交内容");
          //关闭加载框
          this.closeLoading();
        }
      });
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },
    /** 关闭按钮 */
    close() {
      let redirectPath = this.$route.query.redirect;
      if(redirectPath){
        this.$tab.closeOpenPage({ path: redirectPath, query: { t: Date.now() } });
      }else{
        const obj = { path: "/tool/gen", query: { t: Date.now(), pageNum: this.$route.query.pageNum } };
        this.$tab.closeOpenPage(obj);
      }
    },
    /** 字段表格当前点击的行信息 **/
    columnTableCurrentChange(row){
      this.nowColumnTableRow=row
    }
  },
  mounted() {
    const el = this.$refs.dragTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
    const sortable = Sortable.create(el, {
      handle: ".allowDrag",
      onEnd: evt => {
        const targetRow = this.columns.splice(evt.oldIndex, 1)[0];
        this.columns.splice(evt.newIndex, 0, targetRow);
        for (let index in this.columns) {
          this.columns[index].sort = parseInt(index) + 1;
        }
      }
    });
  },
  watch:{
    info:{
      deep: true,
      immediate: true,
      handler:function(val, oldVal){
        this.isShowFormBuildInfo = false;
        if(val['genType'] == '2'){
          //优树搭模式，显示表单配置
          this.isShowFormBuildInfo = true;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>

  .config-divider .el-divider__text{
    font-weight: bold !important;
  }

  .columnInfo-box{
    width: 100%;
    display: flex;

    .column-table{
      //width: 70%;
    }
    .column-config{
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;

      .title{
        width: 100%;
        text-align: center;
        font-weight: bold;
        font-size: 13px;
        height: 43px;
        line-height: 43px;
        border-bottom: 1px solid #EBEEF5;
      }

      .column-form{
        overflow-y: scroll;
        padding: 20px 10px;
      }
    }
  }

</style>
